/// FaiChou  2016.12.28 
/// 为降低模块间的耦合，不必import，只需add & post即可
/// 退出程序最好remove吊

var __notices = [];
var isDebug = false;

/// 注册通知，name: 通知名称，selector: 方法，动作，observer: 注册的Page对象
function addNotification(name, selector, observer) {
	if (name && selector) {
		if (!observer) {
			console.warn("addNotification Warning: need observer");
		}
		if (isDebug) {
			console.log("addNotification:" + name);
		}
		var newNotice = {
			name: name,
			selector: selector,
			observer: observer
		};
		_addNotices(newNotice);
	} else {
		console.error("addNotification error: lack of name or selector");
	}
}

function _addNotices(newNotice) {
	__notices.push(newNotice);
}

/// 移除通知， name: 通知名字，observer: 注册通知所在的Page对象
function removeNotification(name, observer) {
	for (var i = 0; i < __notices.length; i++) {
		var notice = __notices[i];
		if (notice.name === name) {
			if (notice.observer === observer) {
				__notices.splice(i, 1);
				return;
			}
		}
	}
}

/// 发送通知, name: 通知名字， info: 参数
function postNotification(name, info) {
	if (__notices.length == 0) {
		console.error("postNotification error: no notice");
		return;
	}
	for (var i = 0; i < __notices.length; i++) {
		var notice = __notices[i];
		if (notice.name === name) {
			notice.selector(info);
		}
	}
}

module.exports = {
    addNotification: addNotification,
    removeNotification: removeNotification,
    postNotification: postNotification
}








